<template>
  <div class="layout-siderbar">
    <!-- <h5 class="menu-title">{{ title }} </h5> -->
    <keep-alive>
      <el-scrollbar>
        <el-menu
          class="menu-content"
          :default-active="currentActive"
          :collapse="true"
          unique-opened
          @select="selsectMenu"
        >
        <template v-for="menu in menus" :key="menu.path">
          <el-menu-item v-if="!menu.hasSubMenu" :index="menu.path">
            {{ menu.title }}
          </el-menu-item>
          <el-sub-menu v-else :key="menu.path">
            <template #title>{{menu.mainMenu}}</template>
            <el-menu-item v-for="submenu in menu.submenu" :index="submenu.path" :key="submenu.id">
              {{ submenu.title }}
            </el-menu-item>
          </el-sub-menu>
        </template>
        </el-menu>
      </el-scrollbar>
    </keep-alive>
  </div>
</template>
<script setup lang="ts">
  import { menus } from '@/components/common/siderBar/menus'
  import { watch, onMounted, ref, reactive } from 'vue'
  import { useRouter } from 'vue-router'

  const router = useRouter()
  const currentActive = ref() // 默认选中
  const props = defineProps({
    code: {
      type: String,
      required: true
    },
    title: {
      type: String,
      required: false
    }
  })

  const selsectMenu = (index) => {
    currentActive.value = index
    router.push(index)
  }
  const changeCurrentActive = (currentPath) => {
    currentActive.value = currentPath
    menus && menus.forEach(item => {
      if (item.path === currentPath || currentPath.indexOf(item.path) !== -1) {
        currentActive.value = item.path
      } else if (item.hasSubMenu) {
        // 具备子菜单
        item.submenu && item.submenu.forEach(item2 => {
          if (item2.path === currentPath || currentPath.indexOf(item2.path) !== -1) {
            currentActive.value = item2.path
          }
        })
      }
    })
  }

  watch(
    () => router.currentRoute.value.path,
    (toPath) => {
      if(toPath.indexOf(currentActive.value) === -1) {
        changeCurrentActive(toPath)
      }
    },
    {
      immediate: true,
      deep: true
    }
  )
</script>
<style lang="scss">
@use '@/assets/style/variable' as *;

  .layout-siderbar{
    height: calc(100% - $menuHeaderTitleHeight);
    border-right: 1px solid #e9ebef;
    .menu-title {
      width: 100%;
      height: $menuHeaderTitleHeight;
      left: 8%;
      font-size: 14px;
      color: #031129;
      letter-spacing: 0;
      line-height: 60px;
      font-weight: 600;
    }
    .menu-content {
      width: 180px;
      border-right: none;
      .el-menu-item {
        height:40px;
        font-size: 12px;
        &.is-active {
          background: #1A6AFF;   
          border: 1px solid $menuActiveColor;
          border-radius: 2px;
          color: $whiteColor;
        }
      }
    }
  }
</style>